<template>
  <div class="homePageWrap">
    <div class="homePageTitle">
      <div class="logoWrap"></div>
      <h1 class="titleWarp">{{ title }}</h1>
    </div>
    <div class="mainWrap">
      <div class="loginWrap">
        <el-form
          ref="loginFormRef"
          :model="loginData"
          :rules="loginRules"
          class="login-form"
        >
          <!-- 用户名 -->
          <el-form-item prop="username" label="账号：">
            <div class="flex-y-center w-full">
              <el-input
                ref="username"
                v-model="loginData.username"
                name="username"
                size="large"
              />
            </div>
          </el-form-item>

          <el-form-item prop="password" label="密码：">
            <div class="flex-y-center w-full">
              <el-input
                v-model="loginData.password"
                type="password"
                name="password"
                @keyup="checkCapslock"
                @keyup.enter="handleLogin"
                size="large"
                show-password
              />
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            class="w-full btnClass"
            @click.prevent="handleLogin"
            >登 录
          </el-button>
        </el-form>
      </div>
    </div>
    <div class="footerWrap">技术支持：广州玉才科技有限公司</div>
  </div>
</template>

<script setup lang="ts">
import { md5 } from "js-md5";
import { useSettingsStore, useUserStore } from "@/store";
import { LoginData, ExamLoginData } from "@/api/auth/types";
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
defineOptions({
  name: "Login",
  inheritAttrs: false,
});

const userStore = useUserStore();

const router = useRouter();
const route = useRoute();
const { t } = useI18n();

const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定

const loginFormRef = ref(ElForm); // 登录表单ref

const loginData = ref<LoginData>({
  username: "",
  password: "",
});

// const loginData = ref<LoginData>({
//   username: "admin",
//   password: "1A7EC4FFD9243F6F70D0B2241A383892",
// });
const title = computed(() => {
  return route.query?.title || "金砖大赛食品安全快速检测赛项管理系统";
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    idCard: [
      {
        required: true,
        trigger: "blur",
        message: " ",
      },
    ],
    name: [
      {
        required: true,
        trigger: "blur",
        message: " ",
      },
    ],
  };
});

/**
 * 登录
 */
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (loginData.value.password !== "1A7EC4FFD9243F6F70D0B2241A383892") {
        loginData.value.password = md5(loginData.value.password);
      }
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );
          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * 检查输入大小写
 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

onMounted(() => {});
</script>

<style lang="scss" scoped></style>
